<template>
    <view class="w-[750rpx] p-[30rpx]">
        <view class="bg-white rounded-[20rpx] p-[40rpx] shadow-sm">
            <!-- 标题 -->
            <view class="text-center mb-[40rpx]">
                <text class="text-[32rpx] font-bold text-gray-800">健康角色画像</text>
            </view>
            
            <!-- 圆环图容器 -->
            <view class="relative flex justify-center items-center" @tap="handleChartTap">
                <!-- Canvas画布 -->
                <canvas 
                    canvas-id="roleChart"
                    id="roleChart"
                    :style="{ width: canvasSize + 'rpx', height: canvasSize + 'rpx' }"
                    class="absolute"
                />
                
                <!-- 中心头像 -->
                <view class="absolute z-10 flex justify-center items-center">
                    <image 
                        :src="centerImage" 
                        class="rounded-full bg-white shadow-lg transition-transform duration-300 hover:scale-110"
                        :style="{ width: centerImageSize + 'rpx', height: centerImageSize + 'rpx' }"
                        mode="aspectFill"
                    />
                </view>
                
                <!-- 重新播放提示 -->
                <view v-if="!isAnimating" class="absolute bottom-[-40rpx] text-center">
                    <text class="text-[24rpx] text-gray-500">点击重新播放动画</text>
                </view>
            </view>
            
            <!-- 图例说明 -->
            <view class="mt-[60rpx] grid grid-cols-2 gap-[20rpx]">
                <view 
                    v-for="(item, index) in chartData" 
                    :key="index"
                    class="flex items-center mb-[15rpx]"
                >
                    <view 
                        class="w-[30rpx] h-[30rpx] rounded-full mr-[20rpx]"
                        :style="{ backgroundColor: item.color }"
                    />
                    <text class="text-[26rpx] text-gray-600">{{ item.label }}</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import Taro from '@tarojs/taro'

// 画布尺寸
const canvasSize = ref(500)
const centerImageSize = ref(160)

// 中心头像
const centerImage = ref('@/assets/img/wz.png')

// 圆环图数据
const chartData = ref([
    { label: '长寿老年', value: 12, color: '#E8F4FD' },
    { label: '婴幼儿', value: 15, color: '#B3D9FF' },
    { label: '学龄前儿童', value: 13, color: '#7FC7FF' },
    { label: '学龄儿童', value: 11, color: '#4BB3FF' },
    { label: '青年', value: 18, color: '#1A9EFF' },
    { label: '中年', value: 16, color: '#0080E6' },
    { label: '年轻老年', value: 10, color: '#0066CC' },
    { label: '老年', value: 5, color: '#004D99' }
])

// 动画控制
const animationProgress = ref(0)
const isAnimating = ref(false)

// 绘制圆环图
const drawRoleChart = async (progress = 1) => {
    try {
        // 获取Canvas上下文
        const ctx = Taro.createCanvasContext('roleChart')
        
        // 清空画布
        ctx.clearRect(0, 0, canvasSize.value, canvasSize.value)
        
        // 画布中心点
        const centerX = canvasSize.value / 2
        const centerY = canvasSize.value / 2
        
        // 圆环参数
        const outerRadius = centerX * 0.75  // 外圆半径
        const innerRadius = centerX * 0.45  // 内圆半径
        
        // 计算总值
        const totalValue = chartData.value.reduce((sum, item) => sum + item.value, 0)
        
        // 绘制背景圆环
        ctx.beginPath()
        ctx.arc(centerX, centerY, outerRadius, 0, 2 * Math.PI)
        ctx.arc(centerX, centerY, innerRadius, 0, 2 * Math.PI, true)
        ctx.setFillStyle('#f5f5f5')
        ctx.fill()
        
        // 绘制圆环分段
        let currentAngle = -Math.PI / 2  // 从12点钟方向开始
        
        chartData.value.forEach((item, index) => {
            const sweepAngle = (item.value / totalValue) * 2 * Math.PI * progress
            
            // 绘制扇形
            ctx.beginPath()
            ctx.arc(centerX, centerY, outerRadius, currentAngle, currentAngle + sweepAngle)
            ctx.arc(centerX, centerY, innerRadius, currentAngle + sweepAngle, currentAngle, true)
            ctx.closePath()
            
            // 设置颜色
            ctx.setFillStyle(item.color)
            ctx.fill()
            
            // 绘制分割线
            if (progress === 1) {
                ctx.beginPath()
                ctx.moveTo(
                    centerX + Math.cos(currentAngle) * innerRadius,
                    centerY + Math.sin(currentAngle) * innerRadius
                )
                ctx.lineTo(
                    centerX + Math.cos(currentAngle) * outerRadius,
                    centerY + Math.sin(currentAngle) * outerRadius
                )
                ctx.setStrokeStyle('#ffffff')
                ctx.setLineWidth(3)
                ctx.stroke()
            }
            
            // 绘制文字标签
            if (progress === 1) {
                const labelAngle = currentAngle + sweepAngle / 2
                const labelRadius = outerRadius + 35
                const labelX = centerX + Math.cos(labelAngle) * labelRadius
                const labelY = centerY + Math.sin(labelAngle) * labelRadius
                
                ctx.setFillStyle('#666666')
                ctx.setFontSize(20)
                ctx.setTextAlign('center')
                ctx.fillText(item.label, labelX, labelY)
            }
            
            currentAngle += (item.value / totalValue) * 2 * Math.PI
        })
        
        // 绘制内圆的白色背景
        ctx.beginPath()
        ctx.arc(centerX, centerY, innerRadius, 0, 2 * Math.PI)
        ctx.setFillStyle('#ffffff')
        ctx.fill()
        
        // 绘制内圆边框
        ctx.beginPath()
        ctx.arc(centerX, centerY, innerRadius, 0, 2 * Math.PI)
        ctx.setStrokeStyle('#e0e0e0')
        ctx.setLineWidth(2)
        ctx.stroke()
        
        // 提交绘制
        ctx.draw()
        
    } catch (error) {
        console.error('绘制圆环图失败:', error)
    }
}

// 动画绘制
const animateChart = () => {
    if (isAnimating.value) return
    
    isAnimating.value = true
    animationProgress.value = 0
    
    const duration = 1500 // 1.5秒
    const startTime = Date.now()
    
    const animate = () => {
        const elapsed = Date.now() - startTime
        const progress = Math.min(elapsed / duration, 1)
        
        // 使用缓动函数
        const easeProgress = 1 - Math.pow(1 - progress, 3)
        
        animationProgress.value = easeProgress
        drawRoleChart(easeProgress)
        
        if (progress < 1) {
            requestAnimationFrame(animate)
        } else {
            isAnimating.value = false
        }
    }
    
    animate()
}

// 处理图表点击
const handleChartTap = () => {
    if (!isAnimating.value) {
        animateChart()
    }
}

// 组件挂载后绘制图表
onMounted(() => {
    nextTick(() => {
        setTimeout(() => {
            animateChart()
        }, 300)
    })
})
</script>

<style lang="scss">
</style>